package com.example.fundappcation.net;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtils {

    public static RetrofitUtils retrofitUtils = new RetrofitUtils();

    Retrofit retrofit;
    private Retrofit mRetrofit;


    public static RetrofitUtils getInstance() {
        if (retrofitUtils == null) {
            synchronized (RetrofitUtils.class) {
                if (retrofitUtils == null) {
                    retrofitUtils = new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;

    }

    public RetrofitUtils() {
        mRetrofit = new Retrofit.Builder()
                .client(getOkHttp())
                .baseUrl("http://fundgz.1234567.com.cn/")
//                .addConverterFactory(GsonConverterFactory.create()).
                .addConverterFactory(GsonFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())//
                .build();
    }

    private static OkHttpClient getOkHttp() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(chain -> {
            Request builder = chain.request().newBuilder()
                    .addHeader("content-type", "application/json")
                    .build();
            return chain.proceed(builder);
        }).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(3, TimeUnit.SECONDS).build();
        return okHttpClient;
    }


    public <T> T create(Class<T> t) {
        if (mRetrofit == null) {
            throw new NullPointerException(getClass().getSimpleName());
        }
        return mRetrofit.create(t);
    }

}
